//
//  AuctionRecordVC.m
//  phmall
//
//  Created by admin on 2017/12/5.
//  Copyright © 2017年 admin. All rights reserved.
//

#import "ShippingAddressVC.h"
#import "ShippingAddressCell.h"
#import "AddAddressVC.h"

@interface ShippingAddressVC ()<UITableViewDelegate,UITableViewDataSource,ShippingAddressCellDelegate,AddAddressVCDelegate>
@property(nonatomic,strong)UITableView *myTableview;
@property(nonatomic,strong)NSMutableArray *addressArray;
@end

@implementation ShippingAddressVC
-(void)reloadData{
    [self loadDataWithAddress];
}
-(void)editDefault:(UITableViewCell *)cell{
    NSIndexPath *index=[self.myTableview indexPathForCell:cell];
    AddressModel *model=self.addressArray[index.section];
    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"address/edit"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:model.uid forKey:@"uid"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([response[@"ret"] isEqualToString:@"200"]) {
            if ([response[@"data"] isEqualToString:@"1"]) {
                [PublicClass ProgressHUDModeText:@"修改成功" andTime:2 ];
            }else{
                [PublicClass ProgressHUDModeText:@"修改失败" andTime:2 ];
            }
            [self loadDataWithAddress];
        }
    } andFailure:^{
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
    }];
    
}
-(void)removeAddress:(UITableViewCell *)cell{
    NSIndexPath *index=[self.myTableview indexPathForCell:cell];
    AddressModel *model=self.addressArray[index.section];
    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"address/delete"];
    NSMutableDictionary *parametersDic = [NSMutableDictionary dictionary];
    [parametersDic setObject:model.uid forKey:@"uid"];
    [httpTool ZBPostNetDataWith:urlstr withDic:parametersDic andSuccess:^(id responseObject) {
        NSMutableDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([response[@"ret"] isEqualToString:@"200"]) {
            [PublicClass ProgressHUDModeText:Localized(@"删除成功") andTime:2 ];
        }else{
            [PublicClass ProgressHUDModeText:Localized(@"删除失败") andTime:2 ];
        }
         [self loadDataWithAddress];
    } andFailure:^{
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
    }];
}
-(void)addAddressAction{
    if (self.addressArray.count>=3) {
        [PublicClass ProgressHUDModeText:Localized(@"只能添加3个地址,如要添加请删除后再试") andTime:2];
        return;
    }
    
    self.hidesBottomBarWhenPushed=YES;
    AddAddressVC *address=[[AddAddressVC alloc]init];
    address.delegate=self;
    address.title=Localized(@"添加新地址");
    [self.navigationController pushViewController:address animated:YES];
}

- (void)loadDataWithAddress{
    
    NSString *urlstr =  [NSString stringWithFormat:@"%@%@",HomeURL,@"address"];
    [httpTool ZBPostNetDataWith:urlstr withDic:nil andSuccess:^(id responseObject) {
        NSMutableDictionary *response = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
        if ([response[@"ret"] isEqualToString:@"200"]) {
            YYCache *cache = [YYCache cacheWithName:@"address"];
            [cache setObject:response[@"data"] forKey:@"list"];
            [self analysisDataWithMemberInfoDictionary:response[@"data"]];
        }
    } andFailure:^{
        [PublicClass ProgressHUDModeText:Localized(@"网络错误") andTime:2 ];
    }];
}
- (void)analysisDataWithMemberInfoDictionary:(NSMutableArray *)array{
    [self.addressArray removeAllObjects];
    for (NSMutableDictionary *dictionary in array) {
        
        AddressModel *model = [AddressModel yy_modelWithDictionary:dictionary];
        if (model.is_buy) {
            YYCache *cache = [YYCache cacheWithName:@"address"];
            [cache setObject:dictionary forKey:@"default"];
        }
        [self.addressArray addObject:model];
    }
    [self.myTableview reloadData];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    //隐藏标签栏
    self.navBarBgAlpha=@"1.0";
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    UIBarButtonItem* leftBar=[[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"返回"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStyleDone target:self action:@selector(leftBarAction)];
    
    self.navigationItem.leftBarButtonItem=leftBar;
    
    self.title=Localized(@"收货地址");
    
    YYCache *cache = [YYCache cacheWithName:@"address"];
    if ([cache containsObjectForKey:@"list"]) {
        NSMutableArray *index = (NSMutableArray *)[cache objectForKey:@"list"];
        [self analysisDataWithMemberInfoDictionary:index];
        [self.myTableview reloadData];
    }

    [self loadDataWithAddress];
    [self.view addSubview:self.myTableview];
    [self.myTableview mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(0);
        make.left.right.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-49);
    }];
    
    UIButton* addAddress=[UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:addAddress];
    [addAddress setTitle:Localized(@"添加新地址") forState:UIControlStateNormal];
    [addAddress addTarget:self action:@selector(addAddressAction) forControlEvents:UIControlEventTouchUpInside];
    [addAddress setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    addAddress.backgroundColor=[UIColor orangeColor];
    //    [logOut setBackgroundImage:[UIImage imageNamed:@"背景渐变条"] forState:UIControlStateNormal];
    [addAddress mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.offset(49);
        make.bottom.equalTo(self.view).offset(-self.tabBar_height);
        make.left.equalTo(self.view);
        make.right.equalTo(self.view.mas_right);
    }];
    // Do any additional setup after loading the view.
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return self.addressArray.count;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    //总高度
    if (section==0) {
        return 10;
    }else{
        return 0.01;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    return nil;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return nil;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    ShippingAddressCell *cell=[ShippingAddressCell theShareCellWithTableView:tableView];
    AddressModel *model=self.addressArray[indexPath.section];
    cell.model=model;
    cell.delegate=self;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.order) {
        AddressModel *model=self.addressArray[indexPath.section];
        [self.navigationController popViewControllerAnimated:YES];
        if (self.delegate &&[self.delegate respondsToSelector:@selector(SelectAddress:)]) {
            [self.delegate SelectAddress:model];
        }
    }else{
        self.hidesBottomBarWhenPushed=YES;
        AddAddressVC *address=[[AddAddressVC alloc]init];
        AddressModel *model=self.addressArray[indexPath.section];
        address.model=model;
        address.delegate=self;
        address.title=Localized(@"管理收货地址");
        [self.navigationController pushViewController:address animated:YES];
    }
   
    
  
}
-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    //分割线补全
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]){
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
}
-(NSMutableArray *)addressArray{
    if (!_addressArray) {
        _addressArray=[[NSMutableArray alloc]init];
    }
    return _addressArray;
}
//MARK:-GETTER
- (UITableView *)myTableview{
    if (!_myTableview) {
        _myTableview = [[UITableView alloc]initWithFrame:CGRectZero style:UITableViewStyleGrouped];
        _myTableview.delegate = self;
        _myTableview.dataSource = self;
        _myTableview.backgroundColor=[UIColor groupTableViewBackgroundColor];
        _myTableview.separatorStyle = UITableViewCellSeparatorStyleNone;
        _myTableview.showsVerticalScrollIndicator=NO;
        _myTableview.scrollEnabled = YES;
    }
    return _myTableview;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end

